package com.mcy.gles.mesh.square;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;

/**
 * 正方形基类
 * @author Administrator
 *
 */
public class Square {

	// 浮点数组
	protected float vertices[] = {
		      -1.0f,  1.0f, 0.0f,  // 0, Top Left
		      -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
		       1.0f, -1.0f, 0.0f,  // 2, Bottom Right
		       1.0f,  1.0f, 0.0f,  // 3, Top Right
		};

	// 连线顺序
	protected short[] indices = { 0, 1, 2, 0, 2, 3 };

	// float数组缓冲
	protected FloatBuffer vertexBuffer;

	// short数组缓冲
	protected ShortBuffer indexBuffer;

	public Square() {
		// a float is 4 bytes, therefore we 
		// multiply the number if
		// vertices with 4.
		// 申请字节缓冲数组内存空间
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
		// 转换字节编码顺序
		vbb.order(ByteOrder.nativeOrder());
		// 将字节数组缓冲转换为浮点数组缓冲
		vertexBuffer = vbb.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);

		// short is 2 bytes, therefore we multiply 
		// the number if
		// vertices with 2.
		ByteBuffer ibb 
		 = ByteBuffer.allocateDirect(indices.length * 2);
		ibb.order(ByteOrder.nativeOrder());
		indexBuffer = ibb.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
	}

	/**
	 * This function draws our square on screen.
	 * 在屏幕上绘制该正方形
	 * @param gl
	 */
	public void draw(GL10 gl) {
		// Counter-clockwise winding.
		gl.glFrontFace(GL10.GL_CCW); //逆时针摆动
		// Enable face culling.
		gl.glEnable(GL10.GL_CULL_FACE); //启用面裁剪
		// What faces to remove with the face culling.
		gl.glCullFace(GL10.GL_BACK); //面裁剪的对象

		// Enabled the vertices buffer for writing 
		// and to be used during
		// rendering.
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		
		// Specifies the location and data format of an array of vertex
		// coordinates to use when rendering.
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

		gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,GL10.GL_UNSIGNED_SHORT, indexBuffer);

		// Disable the vertices buffer.
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); 
		// Disable face culling.
		gl.glDisable(GL10.GL_CULL_FACE); 
	}

}
